package cn.cuilan.design.singleton;

import java.io.*;

/**
 * 单例模式
 *
 * @author zhang.yan
 * @since 2021/3/18
 */
public class Singleton implements Serializable {

    private static volatile Singleton INSTANCE;

    private static boolean flag = true;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (INSTANCE == null) {
            synchronized (Singleton.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Singleton();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 防止反序列化破坏
     */
    private Object readResolve() {
        return INSTANCE;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        Singleton instance = Singleton.getInstance();
        System.out.println(instance);
        System.out.println(Singleton.getInstance());
        System.out.println(Singleton.getInstance());

//        String fileName = "/Users/zhangyan/instance.obj";
//
//        System.out.println("序列化");
//        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
//        oos.writeObject(instance);
//        oos.close();
//        System.out.println("序列化完成...");
//
//        System.out.println("反序列化");
//        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
//        Singleton s1 = (Singleton) ois.readObject();
//        System.out.println(s1);
//
//        ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream(fileName));
//        Singleton s2 = (Singleton) ois2.readObject();
//        System.out.println(s2);
//
//        System.out.println("反序列化完成...");
//        ois.close();
    }

}
